"""
This scripts is supposed to be ran in linux
There are another scripts to measure the performance
I use date +%s and date to and ps aux|grep openttd, to find the 
cpu and mem usage of it (crontab to run it every second)

I use tshark -f ip -q -w=abc.txt to get the packets of it.
And use wireshark's analysis to output the desire data.

"""
import Process,os,time,  sys
from threading import Timer
from Performance import Performance
from Configuration import Configuration

commands = ["Rondje","Convoy", "PathZilla", "OtviAI", "choochoo", "\"Denver & Rio Grande\"", 
            "AdmiralAI", "PAXLink"]
def setAI(num):
    file = open(game_start_scr_path, "w")
    for i in xrange(0, num/1):
        print >> file, "start_ai " + commands[i]  
    file.close()  

maxAIs = 8
totalTurns = 10

game_start_scr_path = ""
if sys.platform == "win32":
    game_start_scr_path = "c:\\program files\\openttd\\scripts\\game_start.scr"
elif sys.platform.find("linux") >=0 :
    game_start_scr_path = "/home/sq/software/openttd-1.0.4/bin/scripts/game_start.scr"


path = os.path.join("..","test_result")
f = open(os.path.join(path, "networkName"),"a")
if os.path.exists(path) == False:
    os.mkdir(path)
path = os.path.join(path, "1a1")
if os.path.exists(path) == False:
    os.mkdir(path)
measurement = Performance()
measurement.flag = 1
measurement.start()
time.sleep(3)
print >>f, measurement.networkFileName
f.close()
for turn in xrange(1, totalTurns + 1/1):
    filename = os.path.join(path ,"test1a1_result_"+"%d"%turn+".txt")
    file = open(filename,"w")
    print >> file, maxAIs
    for i in xrange(1,maxAIs + 1/1):
        Configuration.removeAutoSave() #It need to remove all the autosave
        #modify the configuration file of openttd.cfg [difficulty] ->max_no_competitors -> i
        Configuration.set("difficulty", "max_no_competitors", i)
        setAI(i)
        print "turn %d"%turn, "AIs %d"%i
        print >> file, "-----------" + time.asctime() + "-----------\n" + "%f"%time.time()
        print >>file , "NumOfAIs " + "%d"%i
    #   we need to use the cygwin to run the openttd, damn. In windows 7 cmd, there are some ini errors
    #   but when we are using the cygwin, there are also errors, so the error is bring about by the ini function    
        if sys.platform == "win32":
            os.system("cygwin.bat") 
        else :
            os.system("~/software/openttd-1.0.4/bin/openttd -g&")
        """
        we need to edit the autoexec.scr under the binary folder, to let it start_ai
        """
        #this call is a block, so i change the script call by cygwin to be background mode
        Process.killOpenTTD()
        print >> file,"%f"%time.time() + "\n-----------" + time.asctime() + "-----------\n"
        file.flush()
measurement.flag = 0

